<template>
  <div class="page-view">
    <div
      v-for="product in payInfo"
      :key="product.GoodsId"
      class="product"
    >
      <img
        v-lazy="product.GoodsImg"
        class="pic"
      >
      <div class="desc">
        <h3 class="name">
          {{ product.GoodsName }}
        </h3>
        <!-- <div class="fit">
          适合人群：{{ product.FitPeople }}
        </div> -->
        <div class="time">
          {{ product.ClassStartTime }} —
          {{ product.ClassEndTime }}
        </div>
        <div class="join-price">
          <div class="join">
            报名人数：{{ product.BuyCount }}
          </div>
          <div class="class-price">
            ￥{{ product.SinglePrice }}
          </div>
        </div>
      </div>
    </div>
    <dl class="choose-pay">
      <dt
        v-if="scholarshipDiscount !== '0.00' && $store.state.instInfo.IsScholarInst"
        class="pay-title"
      >
        <label class="label">奖学金折扣:</label>
        <span class="label-price">-￥{{ scholarshipDiscount }}</span>
      </dt>
      <dt class="pay-title">
        支付方式:
      </dt>
      <!-- <dd
        v-if="availabePayWay=== 1 || availabePayWay === 2"
        class="pay-way"
        @click="choosePayWay('zhifubao')"
      >
        <div class="left">
          <img
            src="~assets/pay/zhifubao.png"
            class="icon"
          >
          <div class="pay-name">
            支付宝支付
          </div>
        </div>
        <img
          v-if="payWay === 'zhifubao'"
          src="~assets/pay/checked.png"
          class="check"
        >
        <img
          v-else
          src="~assets/pay/check.png"
          class="check"
        >
      </dd> -->
      <dd
        v-if="availabePayWay=== 1 || availabePayWay === 3"
        class="pay-way"
        @click="choosePayWay('weixin')"
      >
        <div class="left">
          <img
            src="~assets/pay/weixin.png"
            class="icon"
          >
          <span class="pay-name">
            微信支付
          </span>
        </div>
        <!-- <img
          v-if="payWay === 'weixin'"
          src="~assets/pay/checked.png"
          class="check"
        >
        <img
          v-else
          src="~assets/pay/check.png"
          class="check"
        > -->
      </dd>
    </dl>
    <footer class="pay-footer">
      <div class="pay-sum">
        ¥{{ orderPrice }}
      </div>
      <div
        class="pay-btn"
        :class="{disabled: !canPay}"
        @click="onPay"
      >
        去付款
      </div>
    </footer>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapState } from 'vuex'
import { browser } from '@/lib/utils'
import { PayInfoState } from '@/store/modules/payInfo'
export default Vue.extend({
  data () {
    const origin = location.origin || (location.protocol + '//' + location.host)
    return {
      isInWeixin: browser.isWechat,
      payWay: 'weixin',
      availabePayWay: 4,
      wxConfig: {} as any,
      payInfo: [] as any[],
      orderPrice: null as any,
      scholarshipDiscount: '',
      // appid: 'wxd59947e384e3d44f',
      openId: '',
      redirect_uri: encodeURIComponent(origin + process.env.BASE_URL + '/getWXCode.html'),
      checkStatusInterval: null as any,
      canPayState: true,
    }
  },
  computed: {
    // ...mapState(['payInfo']) as MappedState,
    canPay (): boolean {
      if (!this.canPayState) {
        return false
      }
      if (this.orderPrice === '0.00') {
        return true
      }
      if (this.isInWeixin && !this.$route.query.code) {
        return false
      }
      // if (this.availabePayWay >= 1 && this.availabePayWay <= 3) {
      //   return true
      // }
      // if (this.isInWeixin && !this.openId) {
      //   return false
      // }
      if (this.availabePayWay !== 1 && this.availabePayWay !== 3) {
        return false
      }
      return true
    },
  },
  created () {
    this.fetchProductInfo()
    this.getPayWay()
    if (sessionStorage.getItem('goBackFromWXPay')) {
      sessionStorage.removeItem('goBackFromWXPay')
      this.onPageshow()
    }
  },
  beforeRouteEnter (to, from, next) {
    if (from.name === 'paySuccess' || from.name === 'payFail') {
      next({ name: 'home' })
    } else {
      next()
    }
  },
  beforeRouteLeave (to, from, next) {
    this.$dialog.close()
    // this.checkStatusInterval && clearInterval(this.checkStatusInterval)
    next()
  },
  methods: {
    onPageshow () {
      this.$dialog.confirm({
        message: '请确认微信支付是否完成',
        cancelButtonText: '重新支付',
        confirmButtonText: '已完成支付',
        beforeClose: (action, done) => {
          if (action === 'confirm') {
            this.fetchWXPayStatus(done)
          } else {
            this.checkStatusInterval && clearInterval(this.checkStatusInterval)
            done()
          }
        },
      })
      // setTimeout(() => {
      //   this.$dialog.close()
      // }, 10000)
    },
    fetchWXPayStatus (done: any) {
      this.$axios({
        url: 'shopping/WeChatPayMark',
        data: {
          outTradeNo: this.$route.query.orderNumber,
        },
      }).then(res => {
        if (res === 1) {
          this.$router.push({
            name: 'paySuccess',
          })
        } else {
          this.$router.push({
            name: 'payFail',
          })
        }
        done()
        // if (res === 1 || res === -1) {
        //   done()
        //   clearInterval(this.checkStatusInterval)
        //   this.checkStatusInterval = null
        //   this.$router.push({
        //     name: res === 1 ? 'paySuccess' : 'payFail',
        //   })
        // } else if (!this.checkStatusInterval) {
        //   this.checkStatusInterval = setInterval(() => {
        //     this.fetchWXPayStatus(done)
        //   }, 2000)
        // }
      })
    },
    fetchProductInfo () {
      if (this.$route.query.orderId) {
        this.$axios({
          url: 'shopping/toPayByOrder',
          data: {
            OrderId: this.$route.query.orderId,
          },
        }).then((res: any) => {
          if (res.ResultCode) {
            this.canPayState = false
            this.setProduct(res.Info)
          } else {
            this.setProduct(res)
          }
        })
      } else {
        this.$toast.fail('请重新下单！')
      }
    },
    setProduct (products: any[]) {
      this.$set(this.$data, 'payInfo', products)
      // const price: number = products.reduce((prev, curP) => {
      //   return prev + +curP.BuyPrice
      // }, 0)
      this.orderPrice = products[0].BuyPrice
      this.scholarshipDiscount = products[0].ScholarshipDiscount
      sessionStorage.setItem('product_info-pay', JSON.stringify(products))
    },
    getPayWay () {
      this.$axios({
        url: 'shopping/GetPayMode',
        data: {
          IsMstation: true,
        },
      }).then(res => {
        if (res) {
          this.availabePayWay = res.Status
          // if (res.Status === 3) {
          //   this.selectPayWay = 2
          // }
        }
      })
    },
    choosePayWay (name: string) {
      this.payWay = name
    },
    zeroPay () {
      if (this.orderPrice === '0.00') {
        this.$axios({
          url: 'shopping/NotifyPay',
          data: {
            OutTradeNo: this.$route.query.orderNumber,
          },
        }).then(res => {
          this.$router.push({
            name: 'paySuccess',
          })
        })
        return true
      }
      return false
    },
    onPay () {
      if (!this.canPay) {
        return
      }
      if (this.zeroPay()) {
        return
      }
      const data = {
        Subjects: 'Subjects',
        TradeType: 'MWEB',
        OutTradeNo: this.$route.query.orderNumber,
        Ip: this.$store.state.ip,
        TrainingInstitutionId: void 0,
        Token: void 0,
        Code: this.$route.query.code,
      }
      // 在微信内
      if (browser.isWechat) {
        if (this.wxConfig.appId) {
          this.wechatPay()
          return
        }
        this.$axios({
          url: 'shopping/WeChatPayForWeChatH5',
          data: {
            ...data,
            TradeType: 'JSAPI',
          },
        }).then(res => {
          this.$set(this.$data, 'wxConfig', JSON.parse(res.JsApiParameters))
          this.wechatPay()
        })
      } else {
        // 在浏览器内
        this.$axios({
          url: 'shopping/WeChatPayForH5',
          data,
        }).then(res => {
          if (res.MWebUrl) {
            // let hideToShow = false
            // window.onpagehide = () => {
            //   console.log('pageHide')
            //   hideToShow = true
            // }
            sessionStorage.setItem('goBackFromWXPay', '1')
            location.href = res.MWebUrl
            // setTimeout(() => {
            //   this.onPageshow()
            // }, 1500)
          } else {
            this.$toast(res)
          }
        })
      }
    },
    wechatPay () {
      const onBridgeReady = () => {
        this.onBridgeReady()
      }
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
        }
      } else {
        onBridgeReady()
      }
    },
    onBridgeReady () {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', this.wxConfig,
        res => {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            this.$router.push({
              name: 'paySuccess',
            })
          } else {
            this.$router.push({
              name: 'payFail',
            })
          }
          console.log(res)
        })
    },
  },
})
interface MappedState {
  payInfo: () => PayInfoState
  [k: string]: any
}
</script>

<style lang="scss" scoped>
$bdc: #e9e9e9;
$footerHeight: 98px;
.pay-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 30px;
  color: #666;
  height: 109px;
  padding: 0 24px;
  @include px1border(bottom, $bdc)
}
.label-price {
  color: $error-web;
  font-size: 36px;
}
.pay-way {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120px;
  padding: 0 24px;
  + .pay-way {
    &::before {
      position: absolute;
      left: 104px;
      top: 0;
      right: 0;
      content: '';
      height: 1px;
      background: $bdc;
    }
  }
}
.left {
  display: flex;
  align-items: center;
}
.icon {
  width: 60px;
}
.pay-name {
  color: #333;
  font-size: 30px;
  margin-left: 20px;
}
.check {
  width: 40px;
}
.choose-pay {
  // border-bottom: 1px solid $bdc;
  @include px1bd(bottom, $bdc);
  border-top: 20px solid $bdc;
}
.page-view {
  background: #fff;
  padding-bottom: $footerHeight;
}
.product {
  display: flex;
  padding: 40px 24px;
  align-items: center;
  // border-bottom: 20px solid #f6f6f6;
  + .product {
    padding-top: 0;
  }
}
.pic, .picwp {
  width: 250px;
}
.desc {
  margin-left: 20px;
  width: 432px;
}
.name {
  color: #333;
  font-size: 32px;
  margin-bottom: 18px;
  @include ellipsis;
}
.fit {
  color: #666;
  font-size: 24px;
  margin-bottom: 12px;
  @include ellipsis;
}
.join-price {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 34px;
}
.join {
  color: #A4A9B2;
  font-size: 22px;
}
.class-price {
  font-size: 30px;
  color: $error-web;
}
.time {
  color: #4B515E;
  font-size: 22px;
}
.pay-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  height: $footerHeight;
  background: #fff;
  @include px1border(top, #e9e9e9)
}
.pay-sum, .pay-btn {
  flex: 1;
  display: flex;
  align-items: center;
}
.pay-sum {
  font-size: 36px;
  color: #c30;
  padding-left: 30px;
}
.pay-btn {
  background: $primary-web;
  color: #fff;
  font-size: 32px;
  justify-content: center;
  &.disabled {
    background: $diabled;
  }
  @include active;
}
.iframe {
  // display: none;
  width: 100%;
  height: 100%;
}
</style>
